package tio.study.helloworld.client;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.log4j.Logger;
import org.tio.client.AioClient;
import org.tio.client.ClientChannelContext;
import org.tio.client.ClientGroupContext;
import org.tio.client.ReconnConf;
import org.tio.client.intf.ClientAioHandler;
import org.tio.client.intf.ClientAioListener;
import org.tio.core.Aio;
import org.tio.core.Node;

import tio.study.helloworld.common.HelloPacket;

public class ClientStarter {
	
	private static final Logger log = Logger.getLogger(ClientStarter.class);
	
	/**
	 * 服务器节点（即ip地址+端口）
	 */
	private static Node serverNode = new Node("127.0.0.1",6789);
	/**
	 * handler:编码、解码、消息处理
	 */
	private static ClientAioHandler<Object,HelloPacket,Object> clientHandler = new ClientHandler();
	/**
	 * 事件监听器，可以为null。
	 */
	private static ClientAioListener<Object,HelloPacket,Object> clientListener = null;
	/**
	 * 断链后自动重连，不想自动重连设置为null
	 */
	private static ReconnConf<Object,HelloPacket,Object> reconnconf = new ReconnConf<Object,HelloPacket,Object>(5000L);
	/**
	 * 一组连接共用的上下文对象
	 */
	private static ClientGroupContext<Object,HelloPacket,Object> clientGroupContext = new ClientGroupContext<>(clientHandler,clientListener,reconnconf);
    /**
     * aioClient对象，用于创建并启动客户端服务
     */
	private static AioClient<Object,HelloPacket,Object> aioClient = null;
	/**
	 * 客户端通道连接信息的上下文对象
	 */
	private static ClientChannelContext<Object,HelloPacket,Object> clientChannelContext = null;
	
	/**
	 * 程序启动入口
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		String hostName = null;
		try {
			hostName = InetAddress.getLocalHost().getHostName();
		} catch (UnknownHostException e) {
			log.error("获取ip地址的主机名失败",e);
			e.printStackTrace();
		}
		log.info("客户端"+hostName + "准备连接服务器");
		
		//创建AioClient对象
		aioClient = new AioClient<>(clientGroupContext);
		//客户端通道连接信息
		clientChannelContext = aioClient.connect(serverNode);
		
		//连接上，可以发送信息
		send(hostName);
	}
	
	/**
	 * 
	 * @throws Exception
	 */
	public static void send(String hostName) throws Exception{
		HelloPacket packet = new HelloPacket();
		String str = hostName + "向服务器问好：hello";
		packet.setBody(str.getBytes(HelloPacket.CHARSET));
		Aio.send(clientChannelContext, packet);
	}
}
